package com.yejiali.backend.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yejiali.backend.common.apicode.ResponseCodeEnum;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.OssService;
import com.yejiali.backend.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author:yejiali
 * @Date:2025/7/21-07-21-17:21
 * @Decsription:com.yejiali.backend.service.impl
 * @Version:1.0
 */
@Service
public class OssServiceImpl implements OssService {


    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.secretKey}")
    private String secretKey;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.external_link}")
    private String external_link;


    public Response<String> saveVideo(MultipartFile file, Long userId) {
        // 校验文件是否为空
        if (file.isEmpty()) {
            return Response.error(ResponseCodeEnum.PARAM_ERROR.getCode(),"文件不能为空");
        }
        //校验文件大小
        if (file.getSize() > 8L * 1024 * 1024 * 1024) {
            return Response.error(ResponseCodeEnum.PARAM_ERROR.getCode(),"文件大小超过8G限制");
        }
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!FileUtil.isFileAllowed(extName)) {
            return Response.error(ResponseCodeEnum.PARAM_ERROR.getCode(),"文件类型不允许");
        }
        // 上传文件到OSS,返回完整路径
        String url= null;
        try {
            //上传文件
            url = ossUpload(file, FileUtil.generateFilePath(originalFilename,userId));
        } catch (Exception e) {
            return Response.error(ResponseCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"文件上传失败");
        }
        return Response.success(url,"视频上传成功");

    }

    /**
     * 上传视频封面图
     * @param file
     * @param userId
     * @return
     */
    @Override
    public Response<String> savePicture(MultipartFile file, Long userId) {
        // 校验文件是否为空
        if (file.isEmpty()) {
            return Response.error(ResponseCodeEnum.PARAM_ERROR.getCode(),"文件不能为空");
        }
        //校验文件大小
        if (file.getSize() > 10 * 1024 * 1024) {
            return Response.error(ResponseCodeEnum.PARAM_ERROR.getCode(),"文件大小超过8G限制");
        }
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 上传文件到OSS,返回完整路径
        String url= null;
        try {
            //上传文件
            url = ossUpload(file, FileUtil.generateFilePath(originalFilename,userId));
        } catch (Exception e) {
            return Response.error(ResponseCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"文件上传失败");
        }
        return Response.success(url,"封面上传成功");

    }

    private String ossUpload(MultipartFile file, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //创建上传对象
        UploadManager uploadManager = new UploadManager(cfg);
        //上传到七牛云后保存的文件名
        String key = filePath;
        //密钥配置
        Auth auth = Auth.create(accessKey, secretKey);
        //默认的上传策略
        String upToken = auth.uploadToken(bucketName);
        try {
            //将文件转换为文件流
            InputStream inputStream = file.getInputStream();
            //上传
            com.qiniu.http.Response response = uploadManager.put(inputStream, key, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            //七牛云异常
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        } catch (IOException e) {
            //IO异常
            throw new RuntimeException(e);
        }
        //返回完整路径
        return "http://"+external_link+"/"+key;
    }



}
